<?php


namespace backend\modules\tool\helpers;


use yii\db\Exception;

class DbHelper
{
    public static function GetPdo($driver,$host,$user,$password,$port,$database){
        $dns="$driver:host=$host;dbname=$database;port=$port;charset=UTF8";
        try {
            $pdo = new \PDO($dns, $user, $password);
        }
        catch (\Throwable $throwable){
            throw new Exception("Failed connect server==>{$dns}");
        }
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
//        $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
        if(!$pdo){
            throw new \Exception("Failed connect server==>{$dns}");
        }
        return $pdo;
    }


    public static function getCreateSql(\PDO $pdo,$table){
        $data=$pdo->query("show create table {$table}")->fetch();
        $sql=$data['Create Table'];
        return str_replace("CREATE TABLE","CREATE TABLE IF NOT EXISTS",$sql);
    }

    /**
     * @param \PDO $pdo
     * @return array
     */
    public static function getTables(\PDO $pdo){
        $data=$pdo->query("show tables")->fetchAll();
        $result=[];
        foreach ($data as $datum){
            $result[]=$datum[array_keys($datum)[0]];
        }
        sort($result);
        return $result;
    }
}